import React from "react";
import { Form, NavBar, Button, Input, TextArea } from "antd-mobile";
import { useNavigate, useSearchParams } from "react-router-dom";
import request from "../../utils/request";
import { connect } from "react-redux";
import { useMemo } from "react";

function Login(props) {
    const Navigat = useNavigate();

    const onFinish = async (values) => {
        const { data } = await request.post("/user/login", values);
        if (data.code === 200) {
            localStorage.setItem("userInfo", JSON.stringify(data));
            props.login(data.data);
            Navigat(props.user.address);
        } else {
            alert("账号或密码错误");
        }
    };

    return (
        <div
            className="box"
            style={{
                paddingTop: "45px",

                zIndex: "-1",
            }}
        >
            <div className="box">
                <NavBar
                    onBack={() => {
                        Navigat(window.history.back(-1));
                    }}
                    className="Navigation"
                >
                    登录
                </NavBar>
                <Form
                    onFinish={onFinish}
                    footer={
                        <Button block type="submit" color="primary" size="large">
                            登录
                        </Button>
                    }
                >
                    <Form.Item name="username" label="用户名" rules={[{ required: true, message: "用户名不能为空" }]}>
                        <Input placeholder="请输入用户名" />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[{ required: true, message: "密码不能为空", messages: "用户名或密码错误" }]}
                    >
                        <Input placeholder="请输入密码" />
                    </Form.Item>
                </Form>

                <Button
                    color="primary"
                    fill="none"
                    onClick={() => {
                        Navigat("/reg");
                    }}
                >
                    没有账号？去注册
                </Button>
            </div>
        </div>
    );
}

Login = connect(
    (state) => {
        return {
            user: state,
        };
    },
    (dispatch) => {
        return {
            login(userInfo) {
                dispatch({ type: "login", payload: userInfo });
            },
        };
    }
)(Login);

export default Login;
